package com.ndood.ddd.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class StringUtil {

	/**
	 * 截取字符串
	 */
	public static String substring(String str, int maxLen) {
		if (str == null) {
			return str;
		}
		if (str.length() <= maxLen) {
			return str;
		}
		return str.substring(0, maxLen);
	}

	/**
	 * 判断是否为数字
	 */
	public static boolean isNumber(String str){
		if(StringUtils.isBlank(str)) {
			return false;
		}
		String reg = "^[0-9]+(.[0-9]+)?$";
		return str.matches(reg);
	}

	/**
	 * 加密格式化银行卡
	 */
	public static String encryptFormat(String str, int p, int s) {
		if(StringUtils.isBlank(str)) {
			return str;
		}
		if(str.length()<p+s) {
			return str;
		}
		String prefix = str.substring(0, p);
		String suffix = str.substring(str.length()-s, str.length());
		return prefix + "*********" + suffix;
	}
	
	/**
     * 驼峰格式字符串转换为下划线格式字符串
     * 
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_');
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    
    /**
     * 驼峰命名，首字母大写
     */
    public static String underlineToCamelLarge(String param) {
        String raw = underlineToCamel(param);
        String first = raw.length()>1?raw.substring(0, 1):"";
        String result = raw.replaceFirst(first, first.toUpperCase());
        return result;
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == '_') {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串2
     */
    public static String underlineToCamel2(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }
	
}
